import json
import os
import threading
import time
import queue
from datetime import datetime
from multiprocessing import Process, Queue
from config import ConfigData, Define
from collections import defaultdict
from multi_offline.process_event import process_main


def format_conversion(original_dict):
    # 创建一个默认字典，用来存储转换后的结果，这里使用列表而不是集合以保持顺序
    transformed_dict = defaultdict(list)
    # 遍历原始字典，填充转换后的字典
    for key, value_list in original_dict.items():
        for value in value_list:
            transformed_dict[value].append(key)
    # 将defaultdict转换为普通字典
    result_dict = {k: v for k, v in transformed_dict.items()}

    return result_dict


class Event:
    def __init__(self, file_path):
        self.config_data = ConfigData
        self.format_str = ConfigData["format_str"]
        self.gantry_info = ConfigData["gantry_info"]
        self.route_list = ConfigData["route"]
        self.file_path = file_path
        self.id_dict = {}
        self.id_data = {}
        self.save_path = None

    def init(self):
        info_dict = {}
        for info in self.gantry_info.keys():
            info_dict[info] = [self.gantry_info[info]["up_gantry_id"], self.gantry_info[info]["down_gantry_id"]]
        # 获取门架ID对应的路段编号
        self.id_dict = format_conversion(info_dict)
        for gid in self.id_dict.keys():
            self.id_data[gid] = []
        # 离线log保存地址
        dir_path = os.path.dirname(self.file_path)
        T = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        self.save_path = os.path.join(dir_path, "offline_log", T)
        if not os.path.exists(self.save_path):
            os.makedirs(self.save_path)
        pass

    def data_split(self):
        gantry_id_list = list(self.id_dict.keys())
        with open(self.file_path, 'r') as f:
            while True:
                message = f.readline()
                if not message:  # 如果文件读取完毕，则退出循环
                    break
                try:
                    msg = json.loads(message.strip())
                    GANTRY = msg[Define["GANTRY"]]
                    if GANTRY in gantry_id_list:
                        new_msg = {Define["TIME"]: msg[Define["TIME"]],
                                   Define["TYPE"]: msg[Define["TYPE"]],
                                   Define["PLATE"]: msg[Define["PLATE"]]}
                        self.id_data[GANTRY].append(new_msg)
                except json.JSONDecodeError:
                    print("忽略非JSON格式的日志行")
                    continue
        print("数据读取完毕")

    def run(self):
        for info in self.gantry_info.keys():
            config_data = self.config_data.copy()
            config_data["gantry_info"] = self.gantry_info[info]
            config_data["gantry_info"]["info"] = info
            config_data["log_path"] = self.save_path
            up_data = self.id_data[config_data["gantry_info"]["up_gantry_id"]]
            down_data = self.id_data[config_data["gantry_info"]["down_gantry_id"]]
            p = Process(target=process_main, args=(config_data, up_data, down_data))
            p.start()


if __name__ == '__main__':
    event = Event(r"/home/gj/Download/新建文件夹/卡口相机.log")
    event.init()
    event.data_split()